function sum(x) {
  return function(y) {
    return x+y;
  }
}
sum(1)(2); // 3

/***
 * 题目:
 * 实现：
 *  sum(1).valueOf() => 1;
 *  sum(1,2).valueOf() => 3;
 *  sum(1,2)(3).valueOf() => 6;
 */

function sum(..args) {
  var saveArg = args || [];

  function sub(...ags) {
    saveArg = saveArg.concat(ags);
    return sub;
  }
  sub.valueOf = function() {
    return saveArg.reduce(function(a,b) {
      return a+b;
    });
  }
  return sub;
}

// 类似loadsh实现一个curry函数
function curry(fn) {
  if (typeof fn != 'function') {
    return
  }
  let argsLen = fn.length; // 获得形参个数

  function refunc() { // curry调用之后，返回这个函数
    let saveArgs = []; // 只能放在这一层，如果放在外层，会导致不能多次调用
    saveArgs = saveArgs.concat(Array.prototype.slice.call(arguments));

    if (argsLen <= saveArgs.length) { // 参数已经足够
      return fn.apply(null, saveArgs);
    }

    function sub() {
      saveArgs = saveArgs.concat(Array.prototype.slice.call(arguments));

      if (argsLen <= saveArgs.length) { // 参数已经足够
        return fn.apply(null, saveArgs);
      }
      return sub;
    }
    return sub;
  }

  return refunc;
}

function f(a,b,c) {
  return a+b+c;
}
let afterCur = curry(f);

console.log(afterCur(1,2)(3)); // 6
console.log(afterCur(1)(2)(3)); // 6
console.log(afterCur(1)(2,3)); // 6